package cn.shyouchi.wuguanjia.android.ui.home.security.thread.me;

import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.UserStorageProvider;
import cn.shyouchi.wuguanjia.android.api.profile.ProfileApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.components.storage.UserStorage;
import cn.shyouchi.wuguanjia.android.controls.AdvanceEditDialogFragment;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.EmergenctContactActivity;
import cn.shyouchi.wuguanjia.android.ui.MultiChoicesActivity;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import io.realm.Realm;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.ui.EmergenctContactActivity.EMERGENCY_CONTACT_NAME;
import static cn.shyouchi.wuguanjia.android.ui.EmergenctContactActivity.EMERGENCY_CONTACT_RELATIONSHIP;
import static cn.shyouchi.wuguanjia.android.ui.EmergenctContactActivity.EMERGENCY_CONTACT_TELEPHONE;

public class ProfileUpdateActivity extends BaseActivity {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_height)
    TextView mTvHeight;
    @BindView(R.id.tv_xueli)
    TextView mTvXueli;
    @BindView(R.id.tv_hunyin)
    TextView mTvHunyin;
    @BindView(R.id.tv_addr)
    TextView mTvAddr;
    @BindView(R.id.tv_contact)
    TextView mTvContact;
    @BindView(R.id.tv_com)
    TextView mTvCom;
    @BindView(R.id.tv_hangye)
    TextView mTvHangye;
    @BindView(R.id.tv_jineng)
    TextView mTvJineng;
    @BindView(R.id.tv_qudao)
    TextView mTvQudao;
    @BindView(R.id.tv_jingyan)
    TextView mTvJingyan;
    @BindView(R.id.tv_should)
    TextView mTvShould;


    UserStorage mUserStorage;

    ProfileApi mProfileApi;


    public static final int UPDATE_PROFILE_FIELD_SHENGAO = 0;
    public static final int UPDATE_PROFILE_FIELD_XUELI = 1;
    public static final int UPDATE_PROFILE_FIELD_HUNYIN = 2;
    public static final int UPDATE_PROFILE_FIELD_ADDR = 3;
    public static final int UPDATE_PROFILE_FIELD_CONTACT = 4;
    public static final int UPDATE_PROFILE_FIELD_COM = 5;
    public static final int UPDATE_PROFILE_FIELD_HANGYE = 6;
    public static final int UPDATE_PROFILE_FIELD_SKILL = 7;
    public static final int UPDATE_PROFILE_FIELD_QUDAO = 8;
    public static final int UPDATE_PROFILE_FIELD_JINGYAN = 9;
    public static final int UPDATE_PROFILE_FIELD_NEIRONG = 10;
    public static final int UPDATE_PROFILE_FIELD_BAND = 11;
    public static final int UPDATE_PROFILE_FIELD_SECURITY = 12;


    static final int EDIT_SKILL_REQUEST = 1001, EDIT_INDUSTRY_REQUEST = 1002, EDIT_EMERGENCY_CONTACT_REQUEST = 1003;


    @Override
    public int initContentView() {
        return R.layout.activity_profile_update;
    }

    @Override
    public void initInjector() {
        mUserStorage = UserStorageProvider.Default();
        mProfileApi = new ProfileApi(mContext);

    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        fillDetail();

        LogUtil.json(mUserStorage.getUserData());

    }


    private void fillDetail() {
        mTvHeight.setText(mUserStorage.getUserData().getHeight() + "cm");
        mTvXueli.setText(mUserStorage.getUserData().getGraduate());
        mTvHunyin.setText(mUserStorage.getUserData().getTelephone());
        mTvAddr.setText(mUserStorage.getUserData().getLiving_address());
        mTvContact.setText(trunObjct(mUserStorage.getUserData().getEmergency_contact()));

        mTvCom.setText(mUserStorage.getUserData().getEmployer());
        mTvHangye.setText(trunArray(mUserStorage.getUserData().getIndustry()));
        mTvJineng.setText(trunArray(mUserStorage.getUserData().getSkill()));
        mTvQudao.setText(mUserStorage.getUserData().getChannel());

        mTvJingyan.setText(mUserStorage.getUserData().getWork_experience());
        mTvShould.setText(mUserStorage.getUserData().getWork_content());

    }


    public void upHeight(View view) {
        FilloutProfileActivity.start(this, "身高", String.valueOf(mUserStorage.getUserData().getHeight()), UPDATE_PROFILE_FIELD_SHENGAO, true, InputType.TYPE_CLASS_NUMBER);
    }


    public void upXueLi(View view) {
        graduateEditDialog();

    }


    void graduateEditDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("选择学历");
        builder.setCustomTitle(tvTitle);
        final String[] graduates = new String[]{"小学", "初中", "高中", "专科", "本科", "研究生", "博士"};
        builder.setItems(graduates, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveChange("graduate", graduates[which], UPDATE_PROFILE_FIELD_XUELI);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    void weddingEditDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("婚姻状况");
        builder.setCustomTitle(tvTitle);
        final String[] graduates = new String[]{"未婚", "已婚"};
        builder.setItems(graduates, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveChange("telephone", graduates[which], UPDATE_PROFILE_FIELD_HUNYIN);
                dialog.dismiss();

            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    private void saveChange(String field, final String value, final int type) {

        Map<String, Object> params = new HashMap<>();
        params.put(field, value);
        mProfileApi.upProfile(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult baseRequestResult) {
                        Realm.getDefaultInstance()
                                .executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {

                                        if (type == UPDATE_PROFILE_FIELD_XUELI) {
                                            UserStorageProvider.Default().getUserData().setGraduate(value);
                                        } else if (type == UPDATE_PROFILE_FIELD_HUNYIN) {
                                            UserStorageProvider.Default().getUserData().setTelephone(value);
                                        } else if (type == UPDATE_PROFILE_FIELD_HANGYE) {
                                            UserStorageProvider.Default().getUserData().setIndustry(value);
                                        } else if (type == UPDATE_PROFILE_FIELD_JINGYAN) {
                                            UserStorageProvider.Default().getUserData().setSkill(value);
                                        }else if (type == UPDATE_PROFILE_FIELD_CONTACT) {
                                            UserStorageProvider.Default().getUserData().setEmergency_contact(value);
                                        }else if (type == UPDATE_PROFILE_FIELD_QUDAO) {
                                            UserStorageProvider.Default().getUserData().setChannel(value);
                                        }

//                                      UserStorageProvider.Default().getUserData().setHeight(value);


                                        fillDetail();


                                    }
                                });


                    }
                });
    }


    public void upHunYin(View view) {
        weddingEditDialog();
    }


    public void upAddr(View view) {
        FilloutProfileActivity.start(this, "现居住地", String.valueOf(mUserStorage.getUserData().getLiving_address()), UPDATE_PROFILE_FIELD_ADDR, true, InputType.TYPE_CLASS_TEXT);
    }


    public void upContact(View view) {
        emergencyContactEditTapped();

    }


    public void upCom(View view) {
        FilloutProfileActivity.start(this, "现单位名称", String.valueOf(mUserStorage.getUserData().getEmployer()), UPDATE_PROFILE_FIELD_COM, true, InputType.TYPE_CLASS_TEXT);
    }


    public void upHangye(View view) {

        showIndustryEditDialog();
//        FilloutProfileActivity.start(this, "行业", String.valueOf(mUserStorage.getUserData().getHeight()), UPDATE_PROFILE_FIELD_SHENGAO, true, InputType.TYPE_CLASS_NUMBER);
    }


    public void upSkill(View view) {
//        FilloutProfileActivity.start(this, "技能", String.valueOf(mUserStorage.getUserData().getHeight()), UPDATE_PROFILE_FIELD_SHENGAO, true, InputType.TYPE_CLASS_NUMBER);

        skillEditTapped();

    }


    public void upQudao(View view) {
//        FilloutProfileActivity.start(this, "应聘渠道", String.valueOf(mUserStorage.getUserData().getHeight()), UPDATE_PROFILE_FIELD_SHENGAO, true, InputType.TYPE_CLASS_NUMBER);

    channelEditDialog();
    }

    //
    public void upJingYan(View view) {
        FilloutProfileActivity.start(this, "工作经验", String.valueOf(mUserStorage.getUserData().getWork_experience()), UPDATE_PROFILE_FIELD_JINGYAN, false, InputType.TYPE_CLASS_TEXT);
    }


    public void upNeiRong(View view) {
        FilloutProfileActivity.start(this, "可从事工作内容", String.valueOf(mUserStorage.getUserData().getWork_content()), UPDATE_PROFILE_FIELD_NEIRONG, false, InputType.TYPE_CLASS_TEXT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == 1000) {
            fillDetail();
        }


        if (requestCode == EDIT_INDUSTRY_REQUEST && resultCode == RESULT_OK) {
            ArrayList<String> industryArrayList = data.getStringArrayListExtra("CHOICES");
            saveChange("industry", JSON.toJSONString(industryArrayList), UPDATE_PROFILE_FIELD_HANGYE);
        }
        if (requestCode == EDIT_SKILL_REQUEST && resultCode == RESULT_OK) {
            ArrayList<String> industryArrayList = data.getStringArrayListExtra("CHOICES");
            saveChange("skill", JSON.toJSONString(industryArrayList), UPDATE_PROFILE_FIELD_JINGYAN);
        } else if (requestCode == EDIT_EMERGENCY_CONTACT_REQUEST && resultCode == RESULT_OK) {


            String name = data.getStringExtra(EMERGENCY_CONTACT_NAME);
            String phone = data.getStringExtra(EMERGENCY_CONTACT_TELEPHONE);
            String relation = data.getStringExtra(EMERGENCY_CONTACT_RELATIONSHIP);

            Map<String, Object> contact = new HashMap<>();
            contact.put("name", name);
            contact.put("phone", phone);
            contact.put("relation", relation);
            saveChange("emergency_contact", JSON.toJSONString(contact), UPDATE_PROFILE_FIELD_CONTACT);

        }


    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    private String trunArray(String src) {
        String dst = "";
        try {
            JSONArray array = new JSONArray(src);
            for (int i = 0; i < array.length(); i++) {
                dst += array.get(i);
                if (i != array.length() - 1) {
                    dst += "/";
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return dst;
    }

    private String trunObjct(String src) {

        LogUtil.e(src);

        String dst = "";
        try {
            JSONObject obj = new JSONObject(src);


            dst = dst + obj.getString("name") + "/";
            dst = dst + obj.getString("relation") + "/";
            dst = dst + obj.getString("phone");


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return dst;
    }


    private void skillEditTapped() {

        Intent i = new Intent(this, MultiChoicesActivity.class);
        Bundle b = new Bundle();
        b.putString("title", "技能");
        b.putStringArray("choices", new String[]{"武术", "散打", "拳击", "退伍", "美术", "驾照", "其他"});
        b.putString("edit_dialog_title", "技能");
        b.putString("edit_dialog_hint", "请输入您的技能");
        i.putExtras(b);
        startActivityForResult(i, EDIT_SKILL_REQUEST);
    }

    private void showIndustryEditDialog() {

        Intent i = new Intent(this, MultiChoicesActivity.class);
        Bundle b = new Bundle();
        b.putString("title", "行业");
        b.putStringArray("choices", new String[]{"保安", "消防", "工程", "保洁", "物业", "其他"});
        b.putString("edit_dialog_title", "行业");
        b.putString("edit_dialog_hint", "请输入您的行业");
        i.putExtras(b);
        startActivityForResult(i, EDIT_INDUSTRY_REQUEST);

    }










    void emergencyContactEditTapped() {
        Intent i = new Intent(this, EmergenctContactActivity.class);
        startActivityForResult(i, EDIT_EMERGENCY_CONTACT_REQUEST);
    }

    void channelEditDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("应聘渠道");
        builder.setCustomTitle(tvTitle);
        final String[] graduates = new String[]{"赶集网", "58同城", "劳务介绍所", "朋友介绍"};
        builder.setItems(graduates, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 2) {
                    AdvanceEditDialogFragment dia = AdvanceEditDialogFragment.newInstance(
                            "应聘渠道", "劳务介绍所", "请输入劳务介绍所的名称", "请输入劳务介绍所的电话号码");
                    dia.setClickListener(new AdvanceEditDialogFragment.AdvanceEditDialogListener() {
                        @Override
                        public void onAdvanceEditDialogPositiveClick(DialogFragment dialog, String content1, String content2) {
                            String channel = content1 + "/" + content2;

                            saveChange("channel", channel, UPDATE_PROFILE_FIELD_QUDAO);

                        }
                    });
                    dia.show(getFragmentManager(), "AgentEditDialogFragment");
                } else if (which == 3) {
                    AdvanceEditDialogFragment di = AdvanceEditDialogFragment.newInstance("应聘渠道", "朋友介绍", "请输入朋友的名称", "请输入朋友的电话号码");
                    di.setClickListener(new AdvanceEditDialogFragment.AdvanceEditDialogListener() {
                        @Override
                        public void onAdvanceEditDialogPositiveClick(DialogFragment dialog, String content1, String content2) {
                            String channel = content1 + "/" + content2;
                            saveChange("channel", channel, UPDATE_PROFILE_FIELD_QUDAO);
                        }
                    });
                    di.show(getFragmentManager(), "FriendEditDialogFragment");

                } else {
                    saveChange("channel", graduates[which], UPDATE_PROFILE_FIELD_QUDAO);
                }

            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

}







